package com.ethereal.petmanagement.controller;

import com.ethereal.petmanagement.dto.ResponseDTO;
import com.ethereal.petmanagement.dto.UserDTO;
import com.ethereal.petmanagement.entity.User;
import com.ethereal.petmanagement.service.impl.UserServiceImpl;
import com.ethereal.petmanagement.util.CodeMsg;
import com.ethereal.petmanagement.util.CopyUtil;
import com.ethereal.petmanagement.util.RequestDispatcherUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(urlPatterns = {"*.user"})
public class UserController extends HttpServlet {
    static UserServiceImpl userService = new UserServiceImpl();
    @Override //doPost
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取请求的URI地址信息
        String uri = req.getRequestURI();
        //截取其中的方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
        try {
            //使用反射机制获取在本类中声明了的方法
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 允许访问private方法
            method.setAccessible(true);
            // 执行方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            throw new RuntimeException("调用方法出错！");
        }

    }
    @Override //doGet
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        doPost(req, resp);
    }

    //用户登录功能
    private void login(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        UserDTO userDTO = new UserDTO();
        //将表单数据传入userDTO
        BeanUtils.populate(userDTO, req.getParameterMap());
        //创建session
        HttpSession session = req.getSession();
        userDTO.setCorrectCaptcha((String) session.getAttribute("captcha"));
        //service登录
        ResponseDTO<UserDTO> responseDTO = userService.login(userDTO);
        //结果判断
        if (responseDTO.getCode() == 0){
            resp.sendRedirect("common/home.jsp"); //重定向到home页
            User user = CopyUtil.copy(userDTO, User.class); //转换类型
            session.setAttribute("loginUser", user); //存入登录用户信息
            session.setMaxInactiveInterval(60*30);
            session.removeAttribute("captcha"); //移除验证码缓存
        }else {
            RequestDispatcherUtil.dispatcher(req,resp,responseDTO); //转发到错误页
        }
    }

    //用户注册功能
    private ResponseDTO<Boolean> register(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException, ServletException {
        UserDTO userDTO = new UserDTO();
        //将表单数据传入userDTO
        BeanUtils.populate(userDTO, req.getParameterMap());
        ResponseDTO<Boolean> responseDTO = userService.register(userDTO);
        if (responseDTO.getCode() != 0){
            RequestDispatcherUtil.dispatcher(req, resp, responseDTO);
        }
        req.getRequestDispatcher("login.jsp").forward(req, resp);
        return responseDTO;
    }

    //修改用户信息
    private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        UserDTO userDTO = new UserDTO();
        //传输数据
        BeanUtils.populate(userDTO, req.getParameterMap());
        //获取session
        HttpSession session = req.getSession();
        //获取登录用户的id
        userDTO.setId(((User) session.getAttribute("loginUser")).getId());
        ResponseDTO<Boolean> responseDTO = userService.updateUser(userDTO);
        if (responseDTO.getCode() == 0){
            resp.sendRedirect("");
        }else {
            RequestDispatcherUtil.dispatcher(req, resp, responseDTO);
        }
    }

    //删除用户(注销账户)
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UserDTO userDTO = new UserDTO();
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        userDTO.setId(user.getId());
        ResponseDTO<Boolean> responseDTO = userService.deleteUser(userDTO);
        if (responseDTO.getCode() != 0){
            RequestDispatcherUtil.dispatcher(req, resp, responseDTO);
        }else {
            session.removeAttribute("loginUser");
            resp.sendRedirect("index.jsp");
        }
    }

    //退出登录
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("loginUser");
        resp.sendRedirect("../index.jsp");
    }
}
